<?php

namespace App\Http\Controllers\Api\V1\Requests;

use App\Models\User;

class TransferGoldCashRequest extends FormRequest
{
	protected User $child;

	public function rules()
	{
		return [
			'invite_code' => [
				'required', 'string',
				'min:10','max:10',
				'exists:users',
				$this->inviteCode(),
			],
			'amount' => $this->amount(),
            'pay_code' => $this->paycode(false),
		];
	}

	public function inviteCode()
	{
		return function ($key, $value, $fail) {

			/**
			 * @var User $user
			 */
			$user = $this->user();
			$child = User::where('invite_code', $value)->first();

			if (! $child) {
				return $fail('目标用户不存在');
			} elseif ($child->id == $user->id) {
				return $fail('仅可向他人转出');
			} elseif (empty($child->parent_id)) {
				return $fail('仅可向下级转出');
			} elseif ($child->id < $child->parent->id) {
				return $fail('仅可向下级转出');
			} elseif ($child->id < $user->id) {
				return $fail('仅可向下级转出');
			} elseif ($child->parent_id == $user->parent_id) {
				return $fail('仅可向下级转出');
			} else {
				$this->child = $child;
				return true;
			}
		};
	}

	public function amount()
	{
		return [
            'required',
            'integer',
            function ($key, $value, $fail) {
                if ($value <= 0) {
                    return $fail("请输入正确的金额");
                } elseif ($this->user()->gold_cashes <= 0) {
                    return $fail("可用抢购金不足");
                } elseif ($this->user()->gold_cashes < $value) {
                    return $fail("可用抢购金不足");
                } else {
                    return true;
                }
            }
        ];
	}

	public function getChild(): User
	{
		return $this->child;
	}
}
